package com.sk.sourcecircle.activity.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.BuyCallback;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.common.Constants;
import com.sk.sourcecircle.dialog.BuyTipDialogFragment;
import com.sk.sourcecircle.entity.AlpayInfo;
import com.sk.sourcecircle.entity.AuthResult;
import com.sk.sourcecircle.entity.OrderDetailsBean;
import com.sk.sourcecircle.entity.PayInfoBean;
import com.sk.sourcecircle.entity.PayResult;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.MD5Utils;
import com.sk.sourcecircle.utils.MyUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2018/1/3.
 */

public class WaitPayOrderActivity extends BaseActivity implements HandleDataCallBack, BuyCallback {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.tv_action)
    TextView tvAction;
    @BindView(R.id.event_bg)
    ImageView eventBg;
    @BindView(R.id.event_name)
    TextView eventName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.event_ll)
    RelativeLayout eventLl;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.pay_price)
    TextView payPrice;
    @BindView(R.id.wx_pay)
    RadioButton wxPay;
    @BindView(R.id.zfb_pay)
    RadioButton zfbPay;
    @BindView(R.id.radio_ll)
    RadioGroup radioLl;
    @BindView(R.id.pay)
    TextView pay;

    private OrderDetailsBean.DataBean dataBean;
    private LoadingDialog loadingDialog;
    private int orderId;

    private IWXAPI iwxapi;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @Override
    protected int getContentView() {
        return R.layout.activity_order_wait_pay;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        EventBus.getDefault().register(this);

        iwxapi = WXAPIFactory.createWXAPI(mContext, Constants.WX_ID, true);
        iwxapi.registerApp(Constants.WX_ID);

        dataBean = getIntent().getParcelableExtra("data");
        Glide.with(mContext).load(dataBean.getImg_url()).into(eventBg);
        tvNum.setText(dataBean.getCount() + "");
        tvPrice.setText("￥" + dataBean.getUnit_price());
        eventName.setText(dataBean.getActivity_name());
        tvLocation.setText(dataBean.getCity() + " " + dataBean.getDistrict());
        tvTime.setText(dataBean.getStart_time() + "开始");
        payPrice.setText("￥" + dataBean.getOrder_price());
        orderId = dataBean.getOrder_id();

    }

    @OnClick({R.id.back, R.id.event_ll, R.id.pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.event_ll:
                Intent intent = new Intent(mContext, EventDetailsActivity.class);
                intent.putExtra("id", dataBean.getActivity_id());
                startActivity(intent);
                break;
            case R.id.pay:

                if (MyUtils.isTui(dataBean.getStart_time())) {
                    doPay();
                } else {
                    BuyTipDialogFragment buyTipDialogFragment = new BuyTipDialogFragment();
                    buyTipDialogFragment.setBuyCallback(WaitPayOrderActivity.this);
                    buyTipDialogFragment.show(getSupportFragmentManager(), "buy");
                }
                break;
        }
    }

    private void doPay() {

        if (radioLl.getCheckedRadioButtonId() == R.id.wx_pay) {
            loadingDialog.show();
            AppApi.getPayParams(orderId, WaitPayOrderActivity.this, 10, WaitPayOrderActivity.this);
        } else if (radioLl.getCheckedRadioButtonId() == R.id.zfb_pay) {
            loadingDialog.show();
            AppApi.getAlpayInfo(orderId, WaitPayOrderActivity.this, 12, WaitPayOrderActivity.this);

        } else {
            Toast.makeText(mContext, "请选择一种支付方式!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 10:
                //调起微信支付
                PayInfoBean payInfoBean = JSON.parseObject(result, PayInfoBean.class);
                wxPay(payInfoBean.getData());
                break;
            case 12:
                //调起支付宝支付
                AlpayInfo alpayInfo = JSON.parseObject(result, AlpayInfo.class);
                final String orderStr = alpayInfo.getData();
                alpay(orderStr);
                break;
            case 16:
                OrderDetailsBean orderDetailsBean = JSON.parseObject(result, OrderDetailsBean.class);
                if (orderDetailsBean.getData().getOrder_status() == 1) {
                    Intent intent = new Intent(mContext, WaitPayOrderActivity.class);
                    intent.putExtra("data", orderDetailsBean.getData());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(mContext, OrderDetailsActivity.class);
                    intent.putExtra("data", orderDetailsBean.getData());
                    startActivity(intent);
                }
                finish();
                break;
        }
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();

    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    private void wxPay(PayInfoBean.DataBean weixpaydata) {
        PayReq req = new PayReq();
        req.appId = weixpaydata.getAppid();
        req.partnerId = weixpaydata.getMch_id();
        req.prepayId = weixpaydata.getPrepay_id();
        req.nonceStr = weixpaydata.getNonce_str();
        req.timeStamp = String.valueOf(weixpaydata.getTimeStamp());
        req.packageValue = "Sign=WXPay";
        req.extData = "app data";
        req.sign = genPayReq(weixpaydata);
        iwxapi.sendReq(req);
    }

    private String genPayReq(PayInfoBean.DataBean weixpaydata) {

        // 获取参数的值
        PayReq request = new PayReq();
        request.appId = weixpaydata.getAppid();
        request.partnerId = weixpaydata.getMch_id();
        request.prepayId = weixpaydata.getPrepay_id();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = weixpaydata.getNonce_str();
        request.timeStamp = weixpaydata.getTimeStamp();

        // 把参数的值传进去SortedMap集合里面
        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", request.appId);
        parameters.put("noncestr", request.nonceStr);
        parameters.put("package", request.packageValue);
        parameters.put("partnerid", request.partnerId);
        parameters.put("prepayid", request.prepayId);
        parameters.put("timestamp", request.timeStamp);

        String characterEncoding = "UTF-8";
        String mySign = createSign(characterEncoding, parameters);
        System.out.println("我的签名是：" + mySign);
        return mySign;
    }

    /**
     * 微信支付签名算法sign
     *
     * @param characterEncoding
     * @param parameters
     * @return
     */
    public static String createSign(String characterEncoding,
                                    SortedMap<Object, Object> parameters) {

        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k)
                    && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        Log.v("createSign", sb.toString());
        sb.append("key=dgsay69845SADASEW678Ihasdysa6eww"); //KEY是商户秘钥
        String sign = MD5Utils.MD5Encode(sb.toString(), characterEncoding, true);
        Log.v("createSign", sign);
        return sign;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlerEvent(String s) {
        if (s.equals("pay")) {
            loadingDialog.show();
            AppApi.getOrderDetails(orderId, WaitPayOrderActivity.this, 16, WaitPayOrderActivity.this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void alpay(final String orderInfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(WaitPayOrderActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(mContext, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    loadingDialog.show();
                    AppApi.getOrderDetails(orderId, WaitPayOrderActivity.this, 16, WaitPayOrderActivity.this);
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(mContext,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(mContext,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();

                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    public void sureBuy() {
        doPay();
    }
}
